package com.ccsoft.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

/**
 * 2022年7月15日 14:29:41 聊天室客户端
 */
public class Ch10ChatRoomClient {
    private static final String SERVER_IP="127.0.0.1";
    private static final int PORT = 6666;
    private Selector selector;
    private SocketChannel socketChannel;
    private String username;

    public Ch10ChatRoomClient() throws IOException {
        selector = Selector.open();
        socketChannel = SocketChannel.open(new InetSocketAddress(SERVER_IP,PORT));
        socketChannel.configureBlocking(false);
        socketChannel.register(selector, SelectionKey.OP_READ);
        username = socketChannel.getLocalAddress().toString().substring(1);
        System.out.println("本客户端username:" + username);
    }

    // 发出消息
    public void sendMsg(String msg) throws IOException {
        msg = "[" + username + "] 说：" + msg;
        socketChannel.write(ByteBuffer.wrap(msg.getBytes()));
    }

    // 读取消息
    public void readMsg() throws IOException {
        int readChannels = selector.select();
        if(readChannels <=0) return;
        Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();
        while(keyIterator.hasNext()){
            SelectionKey key = keyIterator.next();
            if(key.isReadable()){
                SocketChannel socketChannel = (SocketChannel)key.channel();
                ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                socketChannel.read(byteBuffer);
                String msg = new String(byteBuffer.array());
            }
            keyIterator.remove();
        }
    }

    public static void main(String[] args) throws IOException {
        Ch10ChatRoomClient client = new Ch10ChatRoomClient();
        new Thread(){
          public void run(){
              try {
                  client.readMsg();
                  Thread.currentThread().sleep(3000);
              } catch (IOException | InterruptedException e) {
                  e.printStackTrace();
              }
          }
        }.start();

        Scanner scanner = new Scanner(System.in);
        while(scanner.hasNextLine()){
            String s = scanner.nextLine();
            client.sendMsg(s);
        }
    }
}
